<template>
  <div>
    <Form ref="form1" :model="formItem" :label-width="120">
      <Row v-show="!switchFlag" class="query-form" style="padding-top: 15px">
        <Col span="8">
          <FormItem label="姓名：">
            <Input class="query-form-el" v-model="formItem.userName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="登录账号：">
            <Input class="query-form-el" v-model="formItem.loginId"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form" style="padding-top: 15px">
        <Col span="8">
          <FormItem label="姓名：">
            <Input class="query-form-el" v-model="formItem.userName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="登录账号：">
            <Input class="query-form-el" v-model="formItem.loginId"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="组织机构搜索：">
            <Input class="query-form-el" placeholder="输入公司名称" v-model="formItem.orgName"></Input>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">

        <Col span="8" offset="16">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form" v-show="!model">
        <Col span="24">
          <Button size="large" type="success" class="ivu-btn-add" icon="md-add" @click="modaltage()">新增
          </Button>
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" :loading="buttonLoading" class="table" no-data-text="没有查询到相关数据!"
           highlight-row stripe border :columns="columns3" width="100%" :data="data1" size="small">
    </Table>
    <Page :total="pagedata.total" :fromPage="pagedata.fromPage" :pageSize="pagedata.pageSize"
          @on-change="pageChange" @on-page-size-change='sizeChange' show-total show-sizer show-elevator/>

    <Modal v-model="modal2" :transfer=false :width=600 :closable="false" :mask-closable="false"
           :title="tage?'修改':'添加'">
      <Form ref="formCustom" :model="formCustom" :rules="ruleCustom" label-position="top">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="姓名" prop="userName">
              <Input type="text" v-model="formCustom.userName"></Input>
              <Input type="text" v-show="false" v-model="formCustom.positionId"></Input>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="登录账号" prop="loginId">
              <Input type="text" v-model="formCustom.loginId"></Input>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="密码：" prop="password">
              <Input type="password" v-model="formCustom.password"></Input>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="岗位" prop="positionId">
              <Select  v-model="formCustom.positionId" @on-open-change="queryPosition">
                <Option v-for="item in positions" :key="item.positionId" :value="item.positionId" :label="item.positionName"></Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="固定电话" prop="contactNumber">
              <Input type="text" v-model="formCustom.contactNumber"></Input>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="手机" prop="mobileNumber">
              <Input type="text" v-model="formCustom.mobileNumber"></Input>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="员工编号" prop="oaUserId">
              <Input type="text" v-model="formCustom.oaUserId"></Input>
            </FormItem>
          </Col>
        </Row>
        <!-- <Row type="flex" justify="center" class="code-row-bg">
             <Col span="23" >
                 <FormItem>
                     <Button    class='ivu-btn-save' @click="modalok()" >确定</Button>
                     <Button type="text"  class='ivu-btn-cancel'  @click="modalcancel" >取消</Button>
                 </FormItem>
             </Col>
         </Row>-->
      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="modalok()">确定</Button>
        <Button type="text" class='ivu-btn-cancel' @click="modalcancel">取消</Button>
      </div>
    </Modal>

    <Modal v-model="orgModal" title="分配组织机构" :styles="{height:'500px'}" class-name='limit-height-dialog'>
      <Tree ref="userOrgInfoTree" :data="orderTree"  :load-data="loadData" show-checkbox multiple ></Tree>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="saveUserOrgs()" >确定</Button>
        <Button type="text"  class='ivu-btn-cancel'  @click="cancelUserOrgs" >取消</Button>
      </div>
    </Modal>
  </div>
</template>

<script>

import {Api} from '../../../api/index.js'
import {sessionStorage} from '@/common/cacheUtils.js';
import zTree from "@/components/ztree.vue"

export default {
  props: ['model', 'companyId', 'companyName'],
  // model:{//其他页面调用 传true
  // companyId:null,//其他页面传当前用户公司组织机构过滤本公司下所有人
  components: {zTree},
  data() {
    return {
      orgModal: false,
      isHead: true,
      ztreeObj: null,
      positions: [],
      switchFlag: false,
      orgId: '',
      orgName: '',
      tableHeight: '',
      buttonLoading: false,
      selectedUserId:"",
      formItem: {
        userName: "",
        loginId: "",
        orgId: ""
      },

      formCustom: {
        userName: '',
        loginId: '',
        orgId: '',
        password: '',
        positionId: '1'
      },
      pagedata: {
        total: 0, //总条数
        fromPage: 1,//从n条开始
        pageSize: 10//每页多少条
      },
      tage: false,
      modal2: false,
      ruleCustom: {
        userName: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        loginId: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
      },
      columns3: [
        {
          // type: 'index',
          title: "序号",
          width: 80,
          align: 'center',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.fromPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          title: '姓名',
          width: 100,
          align: 'center',
          key: 'userName'
        },
        {
          title: '登录账号',
          width: 100,
          align: 'center',
          key: 'loginId',

        },
        {
          title: '二级集团',
          minWidth: 200,
          align: 'center',
          key: 'twoLevelOrgName'
        },
        {
          title: '公司',
          minWidth: 200,
          align: 'center',
          key: 'companyName'
        },
        {
          title: '部门',
          minWidth: 200,
          align: 'center',
          key: 'orgName'
        },
        {
          title: '岗位',
          minWidth: 150,
          align: 'center',
          key: 'positionName'
        },
        {
          title: '操作',
          fixed: 'right',
          align: 'center',
          width: 240,
          render: (h, params) => {
            if (this.model) {
              return h('div', [
                h('A', {
                  props: { type: 'primary', size: 'small' },
                  style: { marginRight: '5px' },
                  on: {
                    click: () => {
                      this.save(params.row);
                    }
                  }
                }, '选择'),
              ]);
            } else {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.modify(params)
                    }
                  }
                }, '修改'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.selectedUserId = params.row.userId;
                      this.orderTree = [
                        {
                          orgId:-1,
                          title: '组织机构',
                          expand: false,
                          loading:true,
                          children:[],
                        }
                      ]
                      this.queryUserOrgsByUserIdAndOrg(params.row.userId,this.orderTree[0].orgId,this.orderTree[0]);
                    }
                  }
                }, '分配组织机构'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                    color: 'red'
                  },
                  on: {
                    click: () => {
                      this.remove(params)
                    }
                  }
                }, '删除')
              ]);
            }
          }
        }
      ],
      data1: [],
      orderTree: [
        {
          orgId:-1,
          title: '组织机构',
          expand: false,
          loading:true,
          children:[],
        }
      ],
      setingTree: {
        check: {
          enable: true
        },
        data: {
          simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
          },
          key:{
            children: "childList"
          },
        },
        view: {
          showIcon: false,
          showLine:true,
          // addHoverDom: this.addHoverDom,
          // removeHoverDom: this.removeHoverDom,
        }
      },
    }
  },
  watch: {
    "modal2": function (qw, er) {
      if (qw && this.tage) {
        setTimeout(() => {
          this.$refs.child.setCurrentOrg();
        }, 100)
      } else {
        this.$refs.child.resetCurrentOrg();
      }
    }
  },
  mounted: function () {
    if (this.model) {
      this.tableHeight = 400
    } else {
      this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    }
    this.query()
  },
  methods: {
    loadData (item, callback) {
      this.$http.get(Api.queryUserOrgsByUserId + "/" + this.selectedUserId + "/" + item.orgId).then(function(res){
        if(res.data.result == true){
          item.checked = false;
          item.selected = false;
          res.data.data.forEach(item1=>{
            item1.loading = false;
            item1.expand = false;
            item1.children = [];
            if(item1.checked == 'false'){
              item1.checked=false;
            }
            else{
              item1.checked=true;
            }
          })
          callback(res.data.data);
        }
      }, function(res){
        this.$Message.error('请求失败');
      });
    },
    queryUserOrgsByUserIdAndOrg(userId,orgId,item){
      this.orgModal = true;
      this.$http.get(Api.queryUserOrgsByUserId + "/" + userId + "/" + orgId).then(function(res){
        if(res.data.result == true){
          item.loading = false;
          item.expand = true;
          res.data.data.forEach(item=>{
            item.loading = false;
            item.expand = false;
            if(item.checked == 'false'){
              item.checked=false;
            }
            else{
              item.checked=true;
            }
            item.children = [];
          })
          if(res.data.data.length>0){
            delete item.checked;
            item.selected = true;
          }
          item.children = res.data.data;
        }
      }, function(res){
        this.$Message.error('请求失败');
      });
    },
    saveUserOrgs(){
      let checkNode = '';
      this.$refs.userOrgInfoTree.getCheckedAndIndeterminateNodes().forEach(item=>{
        if(item.isChild == true || item.children.length == 0 ||item.expand == false){
          checkNode += (item.orgId + "_1,");
        }else{
          checkNode += (item.orgId + "_0,");
        }
      })
      let param = {'orgId':checkNode};
      this.$http.post(Api.addUserOrg + "/" + this.selectedUserId,
          param,{emulateJSON:true}).then(function(res){
        this.orgModal = false;
      })
    },
    cancelUserOrgs(){
      this.orgModal = false;
    },
    treeSelect(nodes,node){

    },
    handleCreated(ztreeObj) {
      this.ztreeObj = ztreeObj;
    },
    save(row){
      this.$emit('getSelectModelData',row);
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 44;
      } else {
        this.tableHeight = this.tableHeight - 44;
      }
    },
    queryPosition(){
      let data = {
        fromPage : 1,
        pageSize : 1000,
        orgId : this.formCustom.orgId
      }
      this.$http.get(Api.queryPosition, {
        params: data
      }).then(res => {
        this.positions = res.data.data;
      })
    },
    orgNamesetOrgInfo(data) {
      this.formCustom.orgId = data[data.length - 1];
    },
    setOrgInfo(data) {
      this.formItem.orgId = data[data.length - 1];
    },
    sizeChange(size) {
      this.pagedata.pageSize = size
      this.query()
    },
    pageChange(pagenum) {
      this.pagedata.fromPage = pagenum
      this.query()
    },
    query() {
      this.buttonLoading = true
      let data = {};
      data.fromPage = this.pagedata.fromPage;
      data.pageSize = this.pagedata.pageSize;

      data = Object.assign(data, JSON.parse(JSON.stringify(this.formItem)));
      data.orgId = this.formItem.orgId;
      if (this.model) {
        data.companyName = this.companyName
      }else{
        data.companyName = sessionStorage('userId').getObject('userId').companyName;
      }
      // let url="http://localhost:30032/envinfo/SaStaffEnvinfo/all"
      let url=Api.queryUser
      this.$http.get(url, {
        params: data
      }).then(res => {
        res.data.data.map(i => {
          if(i.orgInfo != null) {
            i.orgName = i.orgInfo.orgName;
            i.orgId = i.orgInfo.orgId;
            if (i.position != null) {
              i.positionId = i.position.positionId
              i.positionName = i.position.positionName
            }
          }
        })
        this.pagedata.total = res.data.total;
        this.data1 = res.data.data;
        this.buttonLoading = false
      }).catch(e => {
        this.$Message.error('请求失败');
      })
    },
    reset() {
      this.formItem = {
        userName: "",
        loginId: "",
        orgId: "",
      };
      this.query();
    },
    modaltage() {
      this.modal2 = true;
      this.formCustom = {}
    },
    modify(params) {
      this.positions = [];
      this.positions.push({positionId:params.row.positionId,positionName:params.row.positionName})
      this.tage = true;
      this.modal2 = true;
      this.orgId = params.row.orgId;
      this.orgName = params.row.orgName,
          this.formCustom = {
            userId: params.row.userId,
            userName: params.row.userName,
            orgId: params.row.orgId,
            orgName: params.row.orgName,
            positionId: params.row.positionId,
            positionName: params.row.positionName,
            loginId: params.row.loginId,
            email: params.row.email,
            contactNumber: params.row.contactNumber,
            mobileNumber: params.row.mobileNumber
          }
    },
    remove(params) {
      this.$http.get(Api.deleteUser + '/' + params.row.userId).then(res => {
        this.$Message.success('删除成功!');
        this.query();
      }).catch(e => {
        this.$Message.error('请求失败');
      })
      this.$http.get(Api.deleteTaskByUserId + '/' + params.row.userId).then(res => {}).catch(e => {})
    },
    modalok() {
      this.$refs["formCustom"].validate((valid) => {
        if (valid) {
          //console.log( this.formCustom.orgId);
          if (this.tage) {
            // this.formCustom.orgId = this.formCustom.orgId[this.formCustom.orgId.length - 1];
            this.formCustom.orgInfo = {"orgId": this.formCustom.orgId};
            this.formCustom.position = {"positionId":this.formCustom.positionId};
            delete this.formCustom['orgId'];
            console.log(this.formCustom)
            this.$http.post(Api.updateUser, this.formCustom).then(res => {
              this.tage = false
              this.modal2 = false
              this.$Message.success('成功!');
              this.query();
            }).catch(e => {
              this.$Message.error('请求失败');
            })
          } else {
            //this.formCustom.orgId = this.formCustom.orgId[this.formCustom.orgId.length - 1];
            this.formCustom.orgInfo = {"orgId": this.formCustom.orgId};
            this.formCustom.position = {"positionId": this.formCustom.positionId};
            delete this.formCustom['orgId'];
            delete this.formCustom['positionId'];
            this.$http.post(Api.addUser, this.formCustom).then(res => {
              this.modal2 = false
              this.$Message.success('成功!');
              this.query();
            }).catch(e => {
              this.$Message.error('请求失败');
            })
          }
        } else {
          this.$Message.error('不能为空!');
        }
      })
    },
    modalcancel() {
      this.tage = false
      this.modal2 = false
    },
  }

}
</script>

<style lang='css' scoped>
@import '../../../index.css';

</style>
